//
//  CarIsComingView.swift
//  JiaoZiTaxi
//
//  Created by Hu Gang on 2022/10/10.
//

import SwiftUI
import MapKit
import AVFoundation
import CoreImage.CIFilterBuiltins

struct CarIsComingView: View {
    var carOrder : CarOrder = CarOrder.shared
    let timer = Timer.publish(every: 5, on: .main, in: .common).autoconnect()
    @Binding var state : EnumCurrentState
    @Binding var showCancelAlert : Bool
    @Binding var showChatWindow : Bool
    @State var showNewMessageNotification = false
   @State private var isAnimating = false

   @State private var opacity = 0.0

    var body: some View {
        
        GeometryReader { geometry in
            VStack(alignment: .leading){
                Spacer()
                VStack(alignment: .leading,spacing: 10){
                  
                    Text(  String(format: "司机飞速接驾中,预估等待 %@ 分钟".localized(), carOrder.leftTime))
                        .font(.system(size: 16))
                    Text("请前往您的上车地点，准备出发")
                        .font(.system(size: 12))
                        .foregroundColor(Color.gray)
                    createComingView()
                    HStack(spacing: 5){
                        Image("请您耐心等待")
                        Text("请您耐心等待，上车后排落座，安全出行").foregroundColor(.gray).font(.system(size: 12))
                        Spacer()
                    }
                    .frame(maxWidth: .infinity)
                    .padding(.horizontal,15)
                        .padding(.vertical,15)
                        .background(Color(hex: "#FFDDBB"))
                        .clipShape(RoundedRectangle(cornerRadius: 20))
                        .padding(.bottom,20)
                    
                }
                .padding(.horizontal,15)
                       .padding(.vertical,15)
                       .cornerRadius(10)
                       .background(.linearGradient(Gradient(colors: [Color(hex: "#F8FFF8"),Color(hex: "#FCFBE4")]), startPoint: .leading, endPoint: .trailing))
                                  .clipShape(RoundedTopRectangle(cornerRadius: 20))
            }
        }
        .onReceive(NotificationCenter.default.publisher(for: .newMessage), perform: { _ in
            print("new message")
            self.showNewMessageNotification = true
        })
        .onAppear(){
            MapConfig.shared.annotationItems.removeAll()
            let startP = ViewModel.shared.startLocation
            let endP = ViewModel.shared.endLocation
            print("xxxxxx\(startP)-\(endP)xxxxx")
            
//
            
        }
        
        
        
        
//        GeometryReader { geometry in
//            VStack {
//                Spacer()
//                VStack(alignment: .center) {
//                    HStack {
//                        Image("call_car")
//                            .resizable()
//                            .frame(width: 60, height: 40)
//                        Text("已接单").foregroundColor(.black).font(.system(size: 18))
//                        Spacer()
//                    }
//                    VStack() {
//                        HStack(spacing: 50) {
//                            VStack(alignment: .leading) {
//                                Text("\(carOrder.carNo)").foregroundColor(.black).font(.system(size: 24, weight: .medium))
//                                Rectangle().fill(Color(hex: "#F0CCFF")).frame(height:10)
//                                if carOrder.leftTime.count > 0 {
//                                    VStack(spacing: 7) {
//                                        Text("预计等待\(carOrder.leftTime)分钟")
//                                            .foregroundColor(.black)
//                                    }
//                                }
//                            }
//                            Image("call_car_icon")
//                                .resizable()
//                                .frame(width: 125, height: 125)
//                            
//                        }
//                        .padding(10)
//                        HStack {
//                            Button {
//                                print("open chat window...")
//                                self.showChatWindow = true
//                                self.showNewMessageNotification = false
//                            } label: {
//                                VStack {
//                                    ZStack {
//                                        Image("chat").resizable().frame(width: 30, height: 30)
//                                        if self.showNewMessageNotification {
//                                            VStack {
//                                                Spacer()
//                                                Image(systemName: "circle.fill")
//                                                    .frame(width: 10, height: 10)
//                                                    .offset(x: 15, y: -10)
//                                                    .foregroundColor(.red)
//                                                    .opacity(opacity)
//                                                    .onAppear {
//                                                        withAnimation(.easeInOut(duration: 1.0)) {
//                                                            self.opacity = 1.0
//                                                        }
//                                                    }
//                                                    .onDisappear {
//                                                        withAnimation(.easeInOut(duration: 1.0)) {
//                                                            self.opacity = 0.0
//                                                        }
//                                                    }
//                                                Spacer()
//                                            }
//                                        }
//                                    }
//                                    Text("聊天沟通").font(.system(size: 14)).padding(.top,-4).foregroundColor(.black).offset(y:2).frame(width: 80)
//                                }
//                            }
//                            .frame(width: 60, height: 60)
//                            Button {
//                                print("call driver phone...")
//                                guard let number = URL(string: "tel://" + carOrder.driverPhone) else { return }
//                                UIApplication.shared.open(number)
//                            } label: {
//                                VStack {
//                                    Image("service_phone").resizable().frame(width: 30, height: 30)
//                                    Text("司机电话").font(.system(size: 14)).padding(.top,-4).foregroundColor(.black).offset(y:2).frame(width: 80)
//                                }
//                            }
//                            .frame(width: 60, height: 60)
//                        }.padding(.horizontal, 20)
//                    }
//                    .padding(.horizontal , 15)
//                    .padding(.bottom, 10)
//                    .background(.white)
//                    .cornerRadius(16)
//                    .shadow(radius: 0.1)
//                }
//                .padding(20)
//                .frame(width:geometry.size.width)
//                .background(Color(hex: "#F1F4FA"))
//                .cornerRadius(16)
//                .shadow(radius: 4)
//            }
//        } .onReceive(NotificationCenter.default.publisher(for: .newMessage), perform: { _ in
//            print("new message")
//            self.showNewMessageNotification = true
//        })
        
        
        
        /*
         VStack {
             Spacer()
             VStack(alignment: .center) {
                 Rectangle().fill(Color(hex: "FF862F8D")).frame(width: 50,height:10)
                Text("已接单")
                   .font(.title)
                   .foregroundColor(Color.init(hex: "FF862f8d"))
                   .fontWeight(.bold)

                 HStack {
                     Spacer()

                     Text("\(carOrder.carNo)")
                         .font(.system(size:24))
                         .padding()
                         .background(.yellow)
                         .border(.gray,width: 1)
                         .foregroundColor(.black)

                     if carOrder.leftTime.count > 0 {
                         VStack {
                             Text("\(carOrder.leftTime)分钟").foregroundColor(.black).padding(.vertical,5)
                             Text("预计等待").foregroundColor(.black)
                         }.padding(.horizontal,10)
                     }
                     Button {
                         print("delete")
                     } label: {
                         VStack {
                             Image(systemName: "phone.circle").font(.system(size: 48)).foregroundColor(Color(hex: "FF862F8D"))
                             Text("司机电话").font(.system(size: 14)).padding(.top,-2).foregroundColor(.black).frame(width: 80)
                         }
                     }
                     Spacer()
                 }

                 HStack {
//                        Button {
//                            print("cancel...")
//
//                            DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
//                                self.state = .canceling
//                            }
//
//                        } label: {
//                            VStack {
//                                Image(systemName: "trash.circle").font(.system(size: 48)).foregroundColor(Color(hex: "FF862F8D"))
//                                Text("取消订单").font(.system(size: 14)).padding(.top,-2).foregroundColor(.black).frame(width: 80)
//                            }
//                        }

                     Button {
                         print("open chat window...")
                         self.showChatWindow = true
                         self.showNewMessageNotification = false
                     } label: {

                         VStack {
                             ZStack {
                                 Image(systemName: "message.circle").font(.system(size: 48)).foregroundColor(Color(hex: "FF862F8D"))
                                 if showNewMessageNotification {
                                     VStack {
                                         HStack {
                                             Spacer()
                                             Image(systemName: "circle.fill").frame(width: 24,height: 24).foregroundColor(.red)
                                               .opacity(isAnimating ? 0.0 : 1.0)
                                               .animation(Animation.easeInOut(duration: 0.5).repeatForever(autoreverses: true))
                                               .onAppear() {
                                                  self.isAnimating = true
                                               }
                                         }
                                         Spacer()
                                     }
                                 }
                             }
                             .frame(width:48,height:48)

                             Text("聊天沟通").font(.system(size: 14)).padding(.top,-4).foregroundColor(.black).offset(y:2).frame(width: 80)
                         }
                     }

                     /* 2023.11.24 Hidden by Renlifeng's mail.
                     Button {
                         print("delete")
                     } label: {
                         VStack {
                             Image("wechat").resizable().scaledToFit().frame(width: 48,height: 48).foregroundColor(Color(hex: "FF862F8D"))
                             Text("司机微信").font(.system(size: 14)).padding(.top,2).foregroundColor(.black).offset(y:2).frame(width: 80)
                         }
                     }
                      */

                     Button {
                         print("delete")
                     } label: {
                         VStack {
                             Image(systemName: "phone.circle").font(.system(size: 48)).foregroundColor(Color(hex: "FF862F8D"))
                             Text("司机电话").font(.system(size: 14)).padding(.top,-2).foregroundColor(.black).frame(width: 80)
                         }
                     }
                 }
                 .padding()
             }
             .frame(width:geometry.size.width-20)
             .background(.white)
             .cornerRadius(10)
             .offset(x:10)
             .shadow(radius: 8)
         }
         .onReceive(NotificationCenter.default.publisher(for: .newMessage), perform: { _ in
            print("[CarIsComingView] [socket message] new message received...")
            self.isAnimating = false
             self.showNewMessageNotification = true
         })
         */
            
          //  .onReceive(timer) { _ in
//                let now = Date().secondsSince1970
//                let seconds = now - carOrder.startTime
//                carOrder.waitTime = Int(seconds)
//                if let pos = carOrder.carPosition {
//                    carOrder.distance = (carOrder.passengerPosition?.distance(to: pos))!
//                }
//            }
//        }
    }
    
}


extension CarIsComingView {
    
    func createComingView() -> some View {
        VStack{
            HStack(){
                VStack(alignment: .leading){
                    Text("\(carOrder.carNo)")
                        .font(.system(size: 32,weight: .bold))
                    Text("品牌∙型号")
                        .font(.system(size: 14))
                }
                Spacer()
                ZStack{
                    Image("taxi_car")
                        .resizable()
                        .frame(width: 100,height: 80)

                    AsyncImage(url: URL(string: carOrder.headavitor.isEmpty ? "" : carOrder.headavitor) ) { phase in
                        switch phase {
                        case .empty:
                            ProgressView() // 加载中
                        case .success(let image):
                            image
                                .resizable()
                                .frame(width: 40,height: 40)
                        case .failure:
                            Image(systemName: "photo") // 加载失败
                                .resizable()
                                .frame(width: 40,height: 40)
                        @unknown default:
                            EmptyView()
                        }
                        
                    }
                    .clipShape(RoundedRectangle(cornerRadius: 20)) // 先裁剪圆角
                        .overlay(
                            RoundedRectangle(cornerRadius: 20)
                                .stroke(Color.white, lineWidth: 1) // 再添加边框
                        )

                    .offset(x: 40, y: -20)
                }
            }.padding(.horizontal,15)
                .padding(.vertical,15)
            Divider()
            HStack{
                Button {
                    guard let number = URL(string: "tel://" + carOrder.driverPhone) else { return }
                    UIApplication.shared.open(number)
                } label: {
                    Spacer()
                    Image("打电话") // 加载失败
                        .resizable()
                        .frame(width: 20,height: 20)
                    Text("打电话").foregroundColor(.black).font(.system(size: 12))
                    Spacer()
                }
                Divider()
                Button {
                    self.showChatWindow = true
                    self.showNewMessageNotification = false
                } label: {
                    Spacer()
                    ZStack {
                        Image("发信息") // 加载失败
                            .resizable()
                            .frame(width: 20,height: 20)
                        if self.showNewMessageNotification {
                            Image(systemName: "circle.fill")
                                .frame(width: 10, height: 10)
                                .offset(x: 15, y: -10)
                                .foregroundColor(.red)
                                .opacity(opacity)
                                .onAppear {
                                    withAnimation(.easeInOut(duration: 1.0)) {
                                        self.opacity = 1.0
                                    }
                                }
                                .onDisappear {
                                    withAnimation(.easeInOut(duration: 1.0)) {
                                        self.opacity = 0.0
                                    }
                                }
                        }
                    }
                 
                    Text("发信息").foregroundColor(.black).font(.system(size: 12))
                    Spacer()
                }
                Divider()
                Button {
//                    WebSocketService.shared.orderState = .canceling
                    self.showCancelAlert = true
                } label: {
                    Spacer()
                    Image( "取消订单") // 加载失败
                        .resizable()
                        .frame(width: 20,height: 20)
                    Text("取消订单").foregroundColor(.black).font(.system(size: 12))
                    Spacer()
                }
            }.frame(height:44)
        }.background(.white)
            .clipShape(RoundedRectangle(cornerRadius: 16)) // 先裁剪圆角
        

    }
}
